package com.definesys.smecrailtransit.module.Login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;

import com.definesys.smecrailtransit.BuildConfig;
import com.definesys.smecrailtransit.R;
import com.definesys.smecrailtransit.SmecApplication;
import com.definesys.smecrailtransit.SmecManager.SmecDialog.SmecDialog;
import com.definesys.smecrailtransit.SmecManager.SmecKpManager.SmecKpUtils;
import com.definesys.smecrailtransit.SmecManager.SmecRetrofit.BaseSubscriber;
import com.definesys.smecrailtransit.SmecManager.SmecRetrofit.SmecAutoUpdate;
import com.definesys.smecrailtransit.SmecManager.SmecSession.SmecSession;
import com.definesys.smecrailtransit.api.SmecRailApi;
import com.definesys.smecrailtransit.base.SmecBaseActivity;
import com.definesys.smecrailtransit.databinding.ActivityLoginBinding;
import com.definesys.smecrailtransit.module.Login.bean.CheckUpdateBean;
import com.definesys.smecrailtransit.module.Splash.SplashContract;
import com.definesys.smecrailtransit.utils.CommonUtils;
import com.definesys.smecrailtransit.utils.ThreadPoolExecutorUtil;
import com.definesys.smecrailtransit.utils.ToastyUtils;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.mzule.activityrouter.annotation.Router;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;

import java.io.File;
import java.util.HashMap;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by xupeizuo on 2017/7/25.
 */
@Router("LoginActivity")
public class LoginActivity extends SmecBaseActivity<LoginPresenter> implements LoginContract ,SplashContract{


    public static final String LOGIN_FAILURE="LOGIN_FAILURE";
    public static final String LOGIN_SEWITCH="LOGIN_SEWITCH";
    public static final String CHANGE_UPDATE_SUCCESS="CHANGE_UPDATE_SUCCESS";
    public static final String CHANGE_UPDATE_FAILED="CHANGE_UPDATE_FAILED";
    public static boolean isFirst=false;

    private ActivityLoginBinding activityLoginBinding;
    private LoginViewModel loginViewModel;
    private  AlphaAnimation mShowAnimation;

    private Handler mHandler=new Handler();
    private boolean checkUpdate = true;


    @Override
    public LoginPresenter getPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityLoginBinding= DataBindingUtil.setContentView(this, R.layout.activity_login);
        loginViewModel=new LoginViewModel();
        _getDataFromSession();
        activityLoginBinding.setViewModel(loginViewModel);
        _initView();
    }

    private void _getDataFromSession(){
        loginViewModel.setRememberFlag(SmecSession.isRememberAccount());
        if(loginViewModel.rememberFlag){
            loginViewModel.setUsername(SmecSession.getSmecUser().getUserId());
            loginViewModel.setPassword(SmecSession.getSmecUser().getPassWord());
        }
    }

    private void _initView(){
        CommonUtils.hideImmManager(activityLoginBinding.getRoot());
        AlphaAnimation alphaAnimation=new AlphaAnimation(0.3f,1.0f);
        alphaAnimation.setDuration(1500);
        activityLoginBinding.getRoot().startAnimation(alphaAnimation);
        HashMap<String,String> param = new HashMap<>();
        param.put("appVer",BuildConfig.VERSION_NAME);
        param.put("platform", SmecRailApi.SmecCode.PLATFORM);
        param.put("appid",BuildConfig.APPLICATION_ID);
        mPresenter.checkUpdate(param);
        //autologinAnimation();
    }

    private void autologinAnimation(){

        if (loginViewModel.rememberFlag) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    autoLogin();
                }
            }, 1300);
        } else {
            setShowAnimation(activityLoginBinding.loginArea, 3000);
        }
    }

    public  void setShowAnimation( final View view, int duration) {
        if (null == view || duration < 0)
        {
            return;
        }
        if (null != mShowAnimation)
        {
            mShowAnimation.cancel();
        }
        mShowAnimation = new AlphaAnimation(0.0f, 1.0f);
        mShowAnimation.setDuration(duration);
        mShowAnimation.setFillAfter(true);
        mShowAnimation.setAnimationListener(new Animation.AnimationListener()
        {

            @Override
            public void onAnimationStart(Animation arg0)
            {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation arg0)
            {

            }

            @Override
            public void onAnimationEnd(Animation arg0)
            {

            }
        });
        view.startAnimation(mShowAnimation);
    }


    /**
     * 登录或记住密码
     * @param view
     */
    public void operator(View view){

        switch (view.getId()){
            case R.id.smec_login:
                if (TextUtils.isEmpty(loginViewModel.getUsername()) && TextUtils.isEmpty(loginViewModel.getPassword())) {
                    ToastyUtils.showErrorToast(this,"用户名和密码不能为空");
                    return;
                }
                SmecKpUtils.showWithStatus();
                login(loginViewModel.getUsername(),loginViewModel.getPassword());
                break;
            case R.id.login_remember:
                if(loginViewModel.rememberFlag){
                    loginViewModel.setRememberFlag(false);
                    SmecSession.setRememberAccount(false);
                }else {
                    loginViewModel.setRememberFlag(true);
                    SmecSession.setRememberAccount(true);
                }
                activityLoginBinding.invalidateAll();
                break;
        }
    }

    @Override
    public void login(String username, String password) {
        mPresenter.login(username, password);
    }


    @Override
    public void autoLogin() {
        mPresenter.autoLogin();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            appManager.finishAllActivity();
            System.exit(0);
        }
        return false;
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(LOGIN_FAILURE)
            }
    )
    public void loginFailure(Object o){
        if(!isFirst){
            isFirst=true;
            setShowAnimation(activityLoginBinding.loginArea,3000);
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(LOGIN_SEWITCH)
            }
    )

    public void loginSwitch(Object o){
        setShowAnimation(activityLoginBinding.loginArea,3000);
        JPushInterface.setAlias(this, "", new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                if(i==0){
                    Log.e("我是清空别名设置",s+" "+SmecSession.getSmecUser().getUserId());
                }
            }
        });
    }


    /**
     * 检查版本更新成功
     * @param c
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_UPDATE_SUCCESS)
            }
    )
    public void changeUpdateSuccess(CheckUpdateBean c){
        if(!c.getLastest().equals(BuildConfig.VERSION_NAME)) {
            if(c.getPolicy().equals(SmecRailApi.SmecCode.POLICY)){
                NormalDialog normalDialog= SmecDialog.getCheckUpdate(this,"当前版本过低，请更新！");

                normalDialog.setOnBtnClickL(
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                normalDialog.dismiss();
                                autologinAnimation();
                            }
                        },
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                normalDialog.dismiss();
                                startUpdate(c);
                            }
                        });

                normalDialog.show();
            }else{
                NormalDialog normalDialog= SmecDialog.getCheckUpdateNow(this,"当前版本过低，请更新！");

                normalDialog.setOnBtnClickL(
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                normalDialog.dismiss();
                                startUpdate(c);
                            }
                        });
                normalDialog.show();
            }
        }else {
            autologinAnimation();
        }
    }

    /**
     * 检查版本更新失败
     * @param o
     */
    @Subscribe(

            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(CHANGE_UPDATE_FAILED)
            }
    )
    public void changeUpdateFailed(Object o){
        autologinAnimation();
    }


    public void startUpdate(CheckUpdateBean c){
        ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.show();
        SmecAutoUpdate.initAutoUpdate(c.getDownload());
        ThreadPoolExecutorUtil.getFixedThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                File file=SmecAutoUpdate.startDownload(dialog);
                SmecAutoUpdate.installApk(LoginActivity.this,file);
            }
        });
    }
}
